﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using DotNetNuke.Common;
using DotNetNuke.Entities.Host;
using DotNetNuke.Services.Mail;

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;

using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Xsl;


namespace DotNetNuke.Modules.UserDefinedTable
{



  public class TrackingController
  {


    public enum Trigger
    {
      New,
      Update,
      Delete
    }


    private static bool ActionIsTriggered(Trigger Trigger, Hashtable settings)
    {
      return (Utilities.CBoolN(settings[SettingName.TrackingEnabled], false)
        && ((((Trigger == TrackingController.Trigger.New) & Utilities.CBoolN(settings[SettingName.TrackingTriggerOnNew], false))
        || ((Trigger == TrackingController.Trigger.Update) & Utilities.CBoolN(settings[SettingName.TrackingTriggerOnUpdate], false)))
        || ((Trigger == TrackingController.Trigger.Delete) & Utilities.CBoolN(settings[SettingName.TrackingTriggerOnDelete], false))));
    }




    private static string GetEmailAddressList(string mailto, DataSet data)
    {
      List<string> list = new List<string>();
      foreach (string str2 in mailto.Split(new char[] { ';' }))
      {
        if (str2.StartsWith("[") && str2.EndsWith("]"))
        {
          string str3 = str2.Substring(1, str2.Length - 2);
          DataRow[] rowArray = data.Tables[DataSetTableName.Fields].Select(string.Format("{0}='{1}'", FieldsTableColumn.Title, str3));
          if (rowArray.Length == 1)
          {
            str3 = (string)rowArray[0][FieldsTableColumn.Title];
            DataType type = DataType.ByName((string)rowArray[0][FieldsTableColumn.Type]);
            if (type is IEmailAdressSource)
            {
              list.Add(((IEmailAdressSource)type).GetEmailAddress(str3, data.Tables[DataSetTableName.Data].Rows[0]));
            }
          }
        }
        else
        {
          list.Add(str2);
        }
      }
      return string.Join(";", list.ToArray());
    }




    private static void HandleAction(Trigger Trigger, DataSet Data, UserDefinedTableController udtC)
    {
      PrepareDataSet(Data, udtC);
      Hashtable settings = udtC.Settings;
      string strSourceText = Utilities.CStrN(settings[SettingName.TrackingSubject], "");
      string message = Utilities.CStrN(settings[SettingName.TrackingMessage], "");
      string emailAddressList = GetEmailAddressList(Utilities.CStrN(settings[SettingName.TrackingEmailFrom], ""), Data);
      if (emailAddressList.Split(new char[] { ';' }).Length > 1)
        emailAddressList = emailAddressList.Split(new char[] { ';' })[0];
      
      string mailTo = GetEmailAddressList(Utilities.CStrN(settings[SettingName.TrackingEmailTo], ""), Data);
      string cc = GetEmailAddressList(Utilities.CStrN(settings[SettingName.TrackingEmailCc], ""), Data);
      string bcc = GetEmailAddressList(Utilities.CStrN(settings[SettingName.TrackingEmailBcc], ""), Data);
      string replyto = GetEmailAddressList(Utilities.CStrN(settings[SettingName.TrackingEmailReplyTo], ""), Data);
      string script = Utilities.CStrN(settings[SettingName.TrackingScript], "");
      string trigger = string.Empty;

      switch (Trigger)
      {
        case TrackingController.Trigger.New:
          trigger = Utilities.CStrN(settings[SettingName.TrackingTextOnNew], "");
          break;

        case TrackingController.Trigger.Update:
          trigger = Utilities.CStrN(settings[SettingName.TrackingTextOnUpdate], "");
          break;

        case TrackingController.Trigger.Delete:
          trigger = Utilities.CStrN(settings[SettingName.TrackingTextOnDelete], "");
          break;
      }

      if (script == "[AUTO]")
        script = "~/DesktopModules/UserDefinedTable/XslStyleSheets/Tracking/Auto.xsl";
      
      else
        script = Globals.GetPortalSettings().HomeDirectory + script;
      
      strSourceText = new DotNetNuke.Modules.UserDefinedTable.TokenReplace().ReplaceEnvironmentTokens(strSourceText, Data.Tables[DataSetTableName.Data].Rows[0]);
      SendMail(emailAddressList, mailTo, cc, bcc, replyto, strSourceText, Data.GetXml(), message, trigger, script);
    }




    public static void OnAction(Trigger Trigger, DataSet Data, UserDefinedTableController udtC)
    {
      if (ActionIsTriggered(Trigger, udtC.Settings))
        HandleAction(Trigger, Data, udtC);
      
    }




    public static void OnAction(Trigger Trigger, int RowId, UserDefinedTableController udtC)
    {
      if (ActionIsTriggered(Trigger, udtC.Settings))
      {
        DataSet row = udtC.GetRow(RowId);
        HandleAction(Trigger, row, udtC);
      }
    }




    private static void PrepareDataSet(DataSet Data, UserDefinedTableController udtC)
    {
      foreach (string str in DataType.AllDataTypes)
        DataType.ByName(str).RenderValuesToHtmlInsideDataSet(Data, udtC.ModuleID, true);
      
      Data.Tables.Add(udtC.Context());
    }




    private static void SendMail(string from, string mailTo, string cc, string bcc, string replyto, string subject, string data, string message, string trigger, string script)
    {
      XslCompiledTransform transform = new XslCompiledTransform();
      transform.Load(System.Web.HttpContext.Current.Server.MapPath(script));
      using (XmlReader reader = new XmlTextReader(new StringReader(data)))
      {
        using (StringWriter writer = new StringWriter())
        {
          if ( string.IsNullOrEmpty(from) )
            from = Globals.GetPortalSettings().Email;
          
          XsltArgumentList arguments = new XsltArgumentList();
          arguments.AddParam("message", "", message);
          arguments.AddParam("trigger", "", trigger);
          transform.Transform(reader, arguments, writer);
          string str = writer.ToString().Replace("href=\"/", string.Format("href=\"http://{0}/", Globals.GetPortalSettings().PortalAlias.HTTPAlias.Split(new char[] { '/' })[0])).Replace("src=\"/", string.Format("src=\"http://{0}/", Globals.GetPortalSettings().PortalAlias.HTTPAlias.Split(new char[] { '/' })[0]));
          //List<Attachment> list = new List<Attachment>();
          string[] list = null;

          DotNetNuke.Services.Mail.Mail.SendMail(from, mailTo, cc, bcc, replyto, MailPriority.Normal, subject, MailFormat.Html, Encoding.UTF8, str, list, "", "", "", "", DotNetNuke.Entities.Host.Host.EnableSMTPSSL);
        }
      }
    }




  }

}

